package com.seeyon.apps.ext.kingdee.controller;


import com.seeyon.apps.ext.kingdee.util.ArrayUtil;
import com.seeyon.apps.ext.kingdee.util.StringUtil;
import com.seeyon.apps.ext.kingdee.util.TXWebUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

public class DownProxyController extends BaseController {
    private final int BUFFER_SIZE = 1024;
    final public static String requestContentDisposition = "Content-Disposition";
    final public static String requestContentLength = "Content-Length";
    private com.seeyon.apps.ext.kingdee.manager.kingdeeManager kingdeeManager;
    public com.seeyon.apps.ext.kingdee.manager.kingdeeManager getkingdeeManager() {
        if (kingdeeManager == null) {
            kingdeeManager = (com.seeyon.apps.ext.kingdee.manager.kingdeeManager) AppContext.getBean("kingdeeManager");
        }
        return kingdeeManager;
    }
    private void singleDownFile(HttpServletResponse response,File file) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        FileInputStream fin = new FileInputStream(file);
        byte[] bytes = new byte[BUFFER_SIZE];
        long fileLength = file.length();

        int count;
        if (fileLength > 0) {
            try {
                while ((count = fin.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }

            } catch (Exception e) {
                out.flush();
                out.close();
                fin.close();
            } finally {
                out.close();
            }
        }
    }
    public static final String[] imageTypes = {"jpg", "jpeg", "gif", "png", "bmp"};
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String attId = request.getParameter("attId");
        kingdeeManager = getkingdeeManager();

        Map<String, Object> beanMap =  kingdeeManager.geAttachmentFile(attId);

        String docpath = (String)beanMap.get("DOCPATH");
        String fileType = (String)beanMap.get("DOCSUFFIX");
        String docName = (String)beanMap.get("DOCNAME");

        String contentType = null;
        //为了兼容 jdk 1.6
        if ("mp4".equalsIgnoreCase(fileType)) {
            contentType = "video/mpeg4";
        } else if ("bt".equalsIgnoreCase(fileType)) {
            contentType = "application/x-bittorrent";
        } else if ("swftools".equalsIgnoreCase(fileType)) {
            contentType = "application/swftools";
        } else if ("xls".equalsIgnoreCase(fileType)) {
            contentType = "application/vnd.ms-excel";
        } else if ("doc".equalsIgnoreCase(fileType) || "docx".equalsIgnoreCase(fileType)) {
            contentType = "application/msword";
        } else if ("mdb".equalsIgnoreCase(fileType)) {
            contentType = "application/msaccess";
        } else if ("ppt".equalsIgnoreCase(fileType)) {
            contentType = "application/x-ppt";
        } else if ("xml".equalsIgnoreCase(fileType)) {
            contentType = "application/xml";
        } else if ("txt".equalsIgnoreCase(fileType) || "htm".equalsIgnoreCase(fileType) || "html".equalsIgnoreCase(fileType)) {
            contentType = "text/html";
        } else if ("zip".equalsIgnoreCase(fileType)) {
            contentType = "application/x-zip-compressed";
        } else if ("rar".equalsIgnoreCase(fileType)) {
            contentType = "application/x-rar-compressed";
        } else if (ArrayUtil.inArray(imageTypes,fileType,true)) {
            contentType = "image/" + fileType;
        } else if ("js".equalsIgnoreCase(fileType)) {
            contentType = "application/x-javascript";
        } else {
            contentType = "application/msword";
        }

        response.setContentType(contentType);
        response.setBufferSize(BUFFER_SIZE);
        response.setCharacterEncoding("UTF-8");
        //下载时候需要的文件名方式
        //以id方式命名
        if (StringUtil.isEmpty(docName))
        {
            docName = StringUtil.substringAfter(docpath,"/");
        }

        // /home/v2/jc6/upload/
        // /home/oafiles/jc6/upload/
        File downloadFile = null;
        File file = new File(docpath);
        if (file.exists()&&file.isFile())
        {
            downloadFile   = file;
        }
        //-------------
        if (downloadFile==null)
        {
            String newDocpath =  StringUtil.replace(docpath,"/home/oafiles/","/home/v2/");
            file = new File(newDocpath);
            if (file.exists()&&file.isFile())
            {
                downloadFile   = file;
            }
        }
        //-----------------------
        if (downloadFile==null &&  !docpath.startsWith("/"))
        {
            String newDocpath =  "/"+ docpath;
            file = new File(newDocpath);
            if (file.exists()&&file.isFile())
            {
                downloadFile   = file;
            }
        }
        if (downloadFile==null)
        {
            TXWebUtil.print("附件文件没有找到",response);
            return null;
        }
         if ("txt".equalsIgnoreCase(fileType) || "log".equalsIgnoreCase(fileType) || "htm".equalsIgnoreCase(fileType) || "html".equalsIgnoreCase(fileType) || ArrayUtil.inArray(imageTypes,fileType,true))
         {
             //...

         }
         else
         {
             response.setHeader(requestContentLength, Long.toString(downloadFile.length()));
             response.setHeader(requestContentDisposition, "attachment;filename=" + URLEncoder.encode(docName, "UTF-8"));
         }
        singleDownFile( response,downloadFile);
        return null;
    }


}
